//
//  HSYCustomMessageView.m
//  CustomNavigationController
//
//  Created by key on 2017/2/13.
//  Copyright © 2017年 huangsongyao. All rights reserved.
//

#import "HSYCustomMessageView.h"
#import "HSYCustomMessageCell.h"
#import "UIView+Bezier.h"
#import <ReactiveCocoa.h>
#import "MacroFaile.h"

#define DEFAULT_POINT_X                 10.0f
#define DEFAULT_POINT_Y                 10.0f

#define DEFAULT_SIZE_W                  80.0f
#define DEFAULT_SIZE_H                  150.0f

#define MIN_TRANS_FORM_MAKE_SCALE       0.000000000001f
#define MAX_TRANS_FORM_MAKE_SCALE       1.0f

#define TABLE_OFFSET_TOP                10.0f
#define TABLE_RADUIS                    8.0f

#define TRIANGLE_START_OFFSET_LEFT      8.0f
#define TRIANGLE_LEFT_POINT_OFFSET      5.0f
#define TRIANGLE_LEFT_POINT_Y           TABLE_OFFSET_TOP

@interface HSYCustomMessageView ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIView *clearView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, assign, readonly) kHSYCustomMessageAnimationDirectionType direction;
@property (nonatomic, copy) void(^didSelectRow)(id data, NSIndexPath *indexPath);
@property (nonatomic, copy) void(^didRemoveMessage)();
@property (nonatomic, copy) void(^completed)(BOOL finished);

@end

@implementation HSYCustomMessageView

- (instancetype)initWithFrame:(CGRect)frame dataSource:(NSMutableArray *)dataSource raduis:(CGFloat)raduis animationDirection:(kHSYCustomMessageAnimationDirectionType)direction
{
    if (self = [super initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)]) {
        _raduis = raduis;
        _dataSource = dataSource;
        _direction = direction;
        self.backgroundColor = [UIColor clearColor];
        CGPoint anchorPoint = CGPointMake(0, 0);
        switch (direction) {
            case kHSYCustomMessageAnimationDirectionTypeTopLeft:
                anchorPoint = CGPointMake(0, 1);
                break;
            case kHSYCustomMessageAnimationDirectionTypeTopRight:
                anchorPoint = CGPointMake(1, 1);
                break;
            case kHSYCustomMessageAnimationDirectionTypeBottomLeft:
                anchorPoint = CGPointMake(1, 0);
                break;
            case kHSYCustomMessageAnimationDirectionTypeBottomRight:
                anchorPoint = CGPointMake(0, 0);
                break;
            default:
                break;
        }
        
        self.clearView = [[UIView alloc] initWithFrame:self.bounds];
        self.clearView.backgroundColor = [UIColor blackColor];
        self.clearView.alpha = 0.0f;
        [self addSubview:self.clearView];
        
        CGFloat x = TRIANGLE_START_OFFSET_LEFT;
        if (direction == kHSYCustomMessageAnimationDirectionTypeTopRight || direction == kHSYCustomMessageAnimationDirectionTypeBottomRight) {
            x = CGRectGetWidth(frame) - x;
        }
        [self.clearView bezierForTriangleByStartPoint:CGPointMake(x, 0) leftPoint:CGPointMake(x - TRIANGLE_LEFT_POINT_OFFSET, TRIANGLE_LEFT_POINT_Y) rightPoint:CGPointMake(x + TRIANGLE_LEFT_POINT_OFFSET, TRIANGLE_LEFT_POINT_Y) triangleFillColor:[UIColor whiteColor]];
        
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(frame), CGRectGetHeight(frame)) style:UITableViewStylePlain];
        self.tableView.backgroundColor = [UIColor whiteColor];
        self.tableView.layer.cornerRadius = raduis;
        self.tableView.layer.anchorPoint = anchorPoint;
        self.tableView.layer.position = frame.origin;
        self.tableView.transform = CGAffineTransformMakeScale(MIN_TRANS_FORM_MAKE_SCALE, MIN_TRANS_FORM_MAKE_SCALE);
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        [self addSubview:self.tableView];
        
    }
    return self;
}

- (void)backgroundColor:(UIColor *)bgColor
{
    if (!bgColor) {
        return;
    }
    self.tableView.backgroundColor = bgColor;
}

#pragma mark - UITableViewDelegate && UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.dataSource.count > 0) {
        return self.dataSource.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *kCustomIdentifier = @"CustomIdentifier";
    HSYCustomMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:kCustomIdentifier];
    if (!cell) {
        cell = [[HSYCustomMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomIdentifier];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.didSelectRow) {
        self.didSelectRow(self.dataSource[indexPath.row], indexPath);
    }
    [self removeMessageView];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end

#define SHOW_ANIMATION_DURATION             0.35f
#define SHOW_ANIMATION_ALPHA                0.30f

@implementation HSYCustomMessageView (Animation)

- (void)showMessageView
{
    if (!self.tableView) {
        return;
    }
    @weakify(self);
    self.tableView.transform = CGAffineTransformMakeScale(MIN_TRANS_FORM_MAKE_SCALE, MIN_TRANS_FORM_MAKE_SCALE);
    self.clearView.alpha = 0.0f;
    [UIView animateWithDuration:[self.class durations] animations:^{
        @strongify(self);
        self.clearView.alpha = SHOW_ANIMATION_ALPHA;
        self.tableView.transform = CGAffineTransformMakeScale(MAX_TRANS_FORM_MAKE_SCALE, MAX_TRANS_FORM_MAKE_SCALE);
    } completion:^(BOOL finished) {
        @strongify(self);
        if (self.completed) {
            self.completed(finished);
        }
    }];
}

- (void)removeMessageView
{
    if (!self.tableView) {
        return;
    }
    @weakify(self);
    self.clearView.alpha = SHOW_ANIMATION_ALPHA;
    self.tableView.transform = CGAffineTransformMakeScale(MAX_TRANS_FORM_MAKE_SCALE, MAX_TRANS_FORM_MAKE_SCALE);
    [UIView animateWithDuration:[self.class durations] animations:^{
        @strongify(self);
        self.clearView.alpha = 0.0f;
        self.tableView.transform = CGAffineTransformMakeScale(MIN_TRANS_FORM_MAKE_SCALE, MIN_TRANS_FORM_MAKE_SCALE);
    } completion:^(BOOL finished) {
        @strongify(self);
        if (self.didRemoveMessage) {
            self.didRemoveMessage(finished);
            [self removeFromSuperview];
        }
    }];
}

+ (NSTimeInterval)durations
{
    return SHOW_ANIMATION_DURATION;
}

@end

@implementation HSYCustomMessageView (Show)

+ (HSYCustomMessageView *)showMessageViewInView:(UIView *)view byPropertyParams:(NSDictionary <NSNumber *, id>*)params didSelectRowAtIndexPath:(void(^)(id x, NSIndexPath *indexPath))row removeDidMessage:(void(^)())remove completed:(void(^)(BOOL finished))completed
{
    if (params.allValues.count == 0) {
        return nil;
    }
    NSMutableArray *dataSource = params[@(kHSYCustomMessagePropertyTypeDataSource)];
    kHSYCustomMessageAnimationDirectionType direction = (kHSYCustomMessageAnimationDirectionType)[params[@(kHSYCustomMessagePropertyTypeAnimationDirection)] integerValue];
    CGFloat raduis = [params[@(kHSYCustomMessagePropertyTypeRaduis)] floatValue];
    UIColor *bgColor = params[@(kHSYCustomMessagePropertyTypeBgColor)];
    
    CGFloat x = params[@(kHSYCustomMessagePropertyTypePointX)] ? [params[@(kHSYCustomMessagePropertyTypePointX)] floatValue] : DEFAULT_POINT_X;
    CGFloat y = params[@(kHSYCustomMessagePropertyTypePointY)] ? [params[@(kHSYCustomMessagePropertyTypePointY)] floatValue] : DEFAULT_POINT_Y;
    CGFloat w = params[@(kHSYCustomMessagePropertyTypeSizeW)] ? [params[@(kHSYCustomMessagePropertyTypeSizeW)] floatValue] : DEFAULT_SIZE_W;
    CGFloat h = params[@(kHSYCustomMessagePropertyTypeSizeH)] ? [params[@(kHSYCustomMessagePropertyTypeSizeH)] floatValue] : DEFAULT_SIZE_H;
    CGRect rect = CGRectMake(x, y, w, h);
    HSYCustomMessageView *messageView = [[HSYCustomMessageView alloc] initWithFrame:rect dataSource:dataSource raduis:raduis animationDirection:direction];
    messageView.bgColor = bgColor;
    
    messageView.didSelectRow = ^(id data, NSIndexPath *indexPath) {
        if (row) {
            row(data, indexPath);
        }
    };
    messageView.didRemoveMessage = ^() {
        if (remove) {
            remove();
        }
    };
    messageView.completed = ^(BOOL finished) {
        if (completed) {
            completed(finished);
        }
    };
    
    [view addSubview:messageView];
    [messageView showMessageView];
    
    return messageView;
}

@end
